<template>
  <el-dialog
    :model-value="dialogVisible"
    :title="dialogStatus == 'create' ? '新建付费套餐' : '编辑付费套餐'"
    :before-close="handleCloseDialog"
    top="40px"
  >
    <el-form
            ref="dialogAddPaidPackageRef"
            :model="formData"
            status-icon
            :rules="rules"
            :label-width="105"
            >
      <el-form-item label="套餐标题" prop="name">
        <el-input
                v-model.trim="formData.name"
                placeholder="请输入套餐名称，长度2-15个字符"
                :minlength="2"
                :maxlength="15"
                :show-word-limit="true"
        />
      </el-form-item>
      <el-form-item label="套餐副标题" prop="intro">
        <el-input v-model.trim="formData.intro" :rows="3" placeholder="副标题长度20字以内" :minlength="2" :maxlength="30" show-word-limit />
      </el-form-item>
      <el-form-item label="套餐原价(元)" prop="oprice">
        <el-input-number v-model="formData.oprice" :precision="2" :min="0.01" placeholder="请输入套餐原价" />
      </el-form-item>
      <el-form-item label="套餐促销价(元)" prop="pprice">
        <el-input-number v-model="formData.pprice" :precision="2" :min="0.01" placeholder="请输入套餐促销价" />
      </el-form-item>
      <el-form-item label="授权天数(天)" prop="days">
        <el-input v-model.number="formData.days" placeholder="请输入购买后授权天数" />
      </el-form-item>
      <el-form-item label="促销标签" prop="tags">
        <el-select
          v-model="formData.tags"
          multiple
          placeholder="请输入 / 选择促销标签"
          filterable
          allow-create
          default-first-option
          style="width: 100%"
        >
          <el-option
            v-for="(tag, index) in formData.tags"
            :key="tag + index"
            :label="tag"
            :value="tag"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否默认" prop="ifdefault">
        <el-radio-group v-model="formData.ifdefault">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否自动续费" prop="ifcontinuous">
        <el-radio-group v-model="formData.ifcontinuous">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="default" size="mini" @click="handleCloseDialog">取消</el-button>
      <el-button type="primary" size="mini" @click="dialogStatus === 'create' ? handleCreatePaidPackage() : handleUpdatePaidPackage()">确定提交</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import {toRef, ref, reactive } from 'vue'
  import {createMediaPrice, updateMediaPrice} from "@/api/media/price";
  import {ElMessage} from 'element-plus'

  export default {
    name: "AddPaidPackage",
    props: {
      dialogFormData: {
        type: Object,
        required: true
      },
      dialogVisible: {
        type: Boolean,
        default: false
      },
      dialogStatus: {
        type: String,
        default: 'create'
      }
    },
    emits: ['handleCloseDialog', 'handleReloadMediaPrice'],
    setup(props, context) {
      const formData = toRef(props, 'dialogFormData')
      const dialogAddPaidPackageRef = ref(null)
      const validateTags = (rule, value, callback) => {
        if (value) {
          let valid = true
          value.forEach(tag => {
            if(tag.length > 4 || tag.length < 2) {
              valid = false
            }
          })
          if (!valid) {
            callback(new Error('促销标签长度为2-4个中文字符'))
          } else {
            callback()
          }
        }
      }
      const rules = reactive({
        name: [{required: true, message: '请输入套餐名称', trigger: 'blur'}],
        oprice: [
            {required: true, message: '请输入套餐原价', trigger: 'blur'}
          ],
        pprice: [
            {required: true, message: '请输入套餐促销价', trigger: 'blur'}
          ],
        days: [
            {required: true, message: '请输入套餐购买天数', trigger: 'blur'},
            {type: 'integer', message: '只能输入整数', trigger: 'blur'}
        ],
        ifcontinuous: [{required: true, message: '请选择是否自动续费', trigger: 'change'}],
        sequence: [{required: true, message: '请输入套餐排序（正序）', trigger: 'blur'}],
        tags: [{validator: validateTags, trigger: 'change'}]
      })

      const handleCloseDialog = () => {
        context.emit('handleCloseDialog')
      }
      const handleCreatePaidPackage = () => {
        dialogAddPaidPackageRef.value.validate(valid => {
          if (valid) {
            createMediaPrice(formData.value).then(response => {
              if (response.errcode === 0) {
                ElMessage({
                  type: 'success',
                  message: response.msg,
                  duration: 1000,
                  onClose: () => {
                    handleCloseDialog()
                    handleReloadMediaPrice()
                  }
                })
              }
            })
          }
        })
      }
      const handleUpdatePaidPackage = () => {
        dialogAddPaidPackageRef.value.validate(valid => {
          if (valid) {
            updateMediaPrice(formData.value).then(response => {
              if (response.errcode === 0) {
                ElMessage({
                  type: 'success',
                  message: response.msg,
                  duration: 1000,
                  onClose: () => {
                    handleCloseDialog()
                    handleReloadMediaPrice()
                  }
                })
              }
            })
          }
        })
      }
      // 刷新媒资价格套餐列表
      const handleReloadMediaPrice = () => {
        context.emit('handleReloadMediaPrice')
      }
      return {
        formData,
        rules,
        handleCloseDialog,
        dialogAddPaidPackageRef,
        handleCreatePaidPackage,
        handleUpdatePaidPackage,
      }
    }
  }
</script>

<style scoped>

</style>
